package cn.murky.tenant.system.biz.service.impl;

import cn.murky.common.enums.CommonStatus;
import cn.murky.tenant.core.utils.SecurityUtils;
import cn.murky.tenant.system.api.enums.SysNoticeTarget;
import cn.murky.tenant.system.biz.domian.dto.UserNoticePageDTO;
import cn.murky.tenant.system.biz.domian.entity.SysNotice;
import cn.murky.tenant.system.biz.domian.entity.table.SysNoticeReadTableDef;
import cn.murky.tenant.system.biz.domian.entity.table.SysNoticeTableDef;
import cn.murky.tenant.system.biz.domian.vo.UserNoticePageVO;
import cn.murky.tenant.system.biz.enums.UserNoticeReadStatus;
import cn.murky.tenant.system.biz.mapper.SysNoticeMapper;
import cn.murky.tenant.system.biz.service.ISysNoticeService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.time.OffsetDateTime;

import static com.mybatisflex.core.query.QueryMethods.case_;

/**
 * 系统通知service
 *
 * @author hans
 */
@Component
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements ISysNoticeService {


    @Override
    public Page<UserNoticePageVO> getEffectiveList(UserNoticePageDTO dto) {
        SysNoticeTableDef SYS_NOTICE = SysNoticeTableDef.SYS_NOTICE;
        SysNoticeReadTableDef SYS_NOTICE_READ = SysNoticeReadTableDef.SYS_NOTICE_READ;
        return pageAs(dto, QueryWrapper.create()
                .select(SYS_NOTICE.ALL_COLUMNS,
                        case_().when(SYS_NOTICE_READ.ID.isNull()).then(1)
                                .when(SYS_NOTICE_READ.ID.isNotNull()).then(0).end().as(UserNoticePageVO::getReadStatus)
                )
                .leftJoin(SYS_NOTICE_READ)
                .on(SYS_NOTICE.ID.eq(SYS_NOTICE_READ.FK_NOTICE_ID))
                .where(SYS_NOTICE.STATUS.eq(CommonStatus.NORMAL)
                .and(SYS_NOTICE.EXPIRE.ge(OffsetDateTime.now())
                        .or(SYS_NOTICE.EXPIRE.isNull())))
                .and(SYS_NOTICE.TARGET.eq(SysNoticeTarget.TENANT))
                .and(SYS_NOTICE_READ.ID.isNull(dto.getReadStatus()!=null && UserNoticeReadStatus.UNREAD==dto.getReadStatus()))
                .and(SYS_NOTICE_READ.ID.isNotNull(dto.getReadStatus()!=null && UserNoticeReadStatus.READ==dto.getReadStatus()))
                .and(SYS_NOTICE_READ.CREATE_USER.eq(SecurityUtils.getUserId(),dto.getReadStatus()!=null&&UserNoticeReadStatus.UNREAD!=dto.getReadStatus()))
                .orderBy(SYS_NOTICE.CREATE_TIME.desc()), UserNoticePageVO.class);
    }

}
